package com.zsyh.jiujiu.weight;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.interpolator.view.animation.FastOutSlowInInterpolator;

import com.raizlabs.android.dbflow.config.FlowConfig;
import com.raizlabs.android.dbflow.config.FlowManager;
import com.zsyh.jiujiu.R;

import java.util.List;

import chihane.jdaddressselector.AddressProvider;
import chihane.jdaddressselector.AddressSelector;
import chihane.jdaddressselector.DefaultAddressProvider;
import chihane.jdaddressselector.OnAddressSelectedListener;
import chihane.jdaddressselector.model.City;
import chihane.jdaddressselector.model.County;
import chihane.jdaddressselector.model.Province;
import chihane.jdaddressselector.model.Street;
import mlxy.utils.Lists;

/**
 * @ProjectName: livvehelp
 * @Package: com.zsyh.lsb.ui
 * @ClassName:
 * @Description: java类作用描述
 * @Author: zsyh
 * @CreateDate: 2020/9/7 11:59
 * @UpdateUser: liangwanbo
 * @UpdateDate: 2020/9/7 11:59
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
public class DiquSelect implements AdapterView.OnItemClickListener {

    private static final int INDEX_TAB_PROVINCE = 0;
    private static final int INDEX_TAB_CITY = 1;
    private static final int INDEX_TAB_COUNTY = 2;
    private static final int INDEX_TAB_STREET = 3;
    private static final int INDEX_INVALID = -1;
    private static final int WHAT_PROVINCES_SELECTED = 0;
    private static final int WHAT_CITIES_SELECTED = 1;
    private static final int WHAT_COUNTIES_SELECTED = 2;
    private static final int WHAT_STREETS_SELECTED = 3;
    private Handler handler = new Handler(new Handler.Callback() {
        public boolean handleMessage(Message msg) {
            switch(msg.what) {
                case 0:
                    DiquSelect.this.provinces = (List)msg.obj;
                    DiquSelect.this.provinceAdapter.notifyDataSetChanged();
                    DiquSelect.this.listView.setAdapter(DiquSelect.this.provinceAdapter);
                    break;
                case 1:
                    DiquSelect.this.cities = (List)msg.obj;
                    DiquSelect.this.cityAdapter.notifyDataSetChanged();
                    if (Lists.notEmpty(DiquSelect.this.cities)) {
                        DiquSelect.this.listView.setAdapter(DiquSelect.this.cityAdapter);
                        DiquSelect.this.tabIndex = 1;
                    } else {
                        DiquSelect.this.callbackInternal();
                    }
                    break;


            }

            DiquSelect.this.updateTabsVisibility();
            DiquSelect.this.updateProgressVisibility();
            DiquSelect.this.updateIndicator();
            return true;
        }
    });
    private static final AddressProvider DEFAULT_ADDRESS_PROVIDER = new DefaultAddressProvider();
    private  Context context;
    private  LayoutInflater inflater;
    private OnAddressSelectedListener listener;
    private AddressProvider addressProvider;
    private View view;
    private View indicator;
    private TextView textViewProvince;
    private TextView textViewCity;
    private TextView textViewCounty;
    private TextView textViewStreet;
    private ProgressBar progressBar;
    private ListView listView;
    private ProvinceAdapter provinceAdapter;
    private CityAdapter cityAdapter;
   /* private CountyAdapter countyAdapter;
    private StreetAdapter streetAdapter;*/
    private List<Province> provinces;
    private List<City> cities;
    private List<County> counties;
    private List<Street> streets;
    private int provinceIndex;
    private int cityIndex;
    private int countyIndex;
    private int streetIndex;
    private int tabIndex;

    public DiquSelect(Context context) {
        this.addressProvider = DEFAULT_ADDRESS_PROVIDER;
        this.provinceIndex = -1;
        this.cityIndex = -1;
        this.countyIndex = -1;
        this.streetIndex = -1;
        this.tabIndex = 0;
        this.context = context;
        this.inflater = LayoutInflater.from(context);
        FlowManager.init((new FlowConfig.Builder(context)).build());
        this.initViews();
        this.initAdapters();
        this.initProvince();
    }

    private void initAdapters() {
        this.provinceAdapter = new ProvinceAdapter();
        this.cityAdapter = new CityAdapter();
       /* this.countyAdapter = new CountyAdapter();
        this.streetAdapter = new StreetAdapter();*/
    }

    private void initProvince() {
        this.retrieveProvinces();
    }

    @SuppressLint("WrongConstant")
    private void updateTabsVisibility() {
        this.textViewProvince.setVisibility(Lists.notEmpty(this.provinces) ? 0 : 8);
        this.textViewCity.setVisibility(Lists.notEmpty(this.cities) ? 0 : 8);
        this.textViewCounty.setVisibility(Lists.notEmpty(this.counties) ? 0 : 8);
        this.textViewStreet.setVisibility(Lists.notEmpty(this.streets) ? 0 : 8);
        this.textViewProvince.setEnabled(this.tabIndex != 0);
        this.textViewCity.setEnabled(this.tabIndex != 1);
        this.textViewCounty.setEnabled(this.tabIndex != 2);
        this.textViewStreet.setEnabled(this.tabIndex != 3);
    }

    private void initViews() {
        this.view = this.inflater.inflate(R.layout.address_selector, (ViewGroup)null);
        this.progressBar = (ProgressBar)this.view.findViewById(R.id.progressBar);
        this.listView = (ListView)this.view.findViewById(R.id.listView);
        this.indicator = this.view.findViewById(R.id.indicator);
        this.textViewProvince = (TextView)this.view.findViewById(R.id.textViewProvince);
        this.textViewCity = (TextView)this.view.findViewById(R.id.textViewCity);
        this.textViewCounty = (TextView)this.view.findViewById(R.id.textViewCounty);
        this.textViewStreet = (TextView)this.view.findViewById(R.id.textViewStreet);
        this.textViewProvince.setOnClickListener(new OnProvinceTabClickListener());
        this.textViewCity.setOnClickListener(new OnCityTabClickListener());
        /*this.textViewCounty.setOnClickListener(new onCountyTabClickListener());
        this.textViewStreet.setOnClickListener(new OnStreetTabClickListener());*/
        this.listView.setOnItemClickListener(this);
        this.updateIndicator();
    }

    private void updateIndicator() {
        this.view.post(new Runnable() {
            public void run() {
                switch(DiquSelect.this.tabIndex) {
                    case 0:
                        DiquSelect.this.buildIndicatorAnimatorTowards(DiquSelect.this.textViewProvince).start();
                        break;
                    case 1:
                        DiquSelect.this.buildIndicatorAnimatorTowards(DiquSelect.this.textViewCity).start();
                        break;
                    case 2:
                        DiquSelect.this.buildIndicatorAnimatorTowards(DiquSelect.this.textViewCounty).start();
                        break;
                    case 3:
                        DiquSelect.this.buildIndicatorAnimatorTowards(DiquSelect.this.textViewStreet).start();
                }

            }
        });
    }

    private AnimatorSet buildIndicatorAnimatorTowards(TextView tab) {
        ObjectAnimator xAnimator = ObjectAnimator.ofFloat(this.indicator, "X", new float[]{this.indicator.getX(), tab.getX()});
        final ViewGroup.LayoutParams params = this.indicator.getLayoutParams();
        ValueAnimator widthAnimator = ValueAnimator.ofInt(new int[]{params.width, tab.getMeasuredWidth()});
        widthAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            public void onAnimationUpdate(ValueAnimator animation) {
                params.width = (Integer)animation.getAnimatedValue();
                DiquSelect.this.indicator.setLayoutParams(params);
            }
        });
        AnimatorSet set = new AnimatorSet();
        set.setInterpolator(new FastOutSlowInInterpolator());
        set.playTogether(new Animator[]{xAnimator, widthAnimator});
        return set;
    }

    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        switch(this.tabIndex) {
            case 0:
                Province province = this.provinceAdapter.getItem(position);
                this.textViewProvince.setText(province.name);
                this.textViewCity.setText("请选择");
                this.textViewCounty.setText("请选择");
                this.textViewStreet.setText("请选择");
                this.provinceAdapter.notifyDataSetChanged();
                this.retrieveCitiesWith(province.id);
                this.cities = null;
                this.counties = null;
                this.streets = null;
                this.cityAdapter.notifyDataSetChanged();
                this.provinceIndex = position;
                this.cityIndex = -1;
                this.countyIndex = -1;
                this.streetIndex = -1;
                break;
            case 1:
                City city = this.cityAdapter.getItem(position);
                this.textViewCity.setText(city.name);
                this.textViewCounty.setText("请选择");
                this.textViewStreet.setText("请选择");
                this.retrieveCountiesWith(city.id);
                this.counties = null;
                this.streets = null;
                this.cityIndex = position;
                this.countyIndex = -1;
                this.streetIndex = -1;
                this.cityAdapter.notifyDataSetChanged();
                this.callbackInternal();
                break;

        }

        this.updateTabsVisibility();
        this.updateIndicator();
    }

    public View getView() {
        return this.view;
    }

    private void callbackInternal() {
        if (this.listener != null) {
            Province province = this.provinces != null && this.provinceIndex != -1 ? (Province)this.provinces.get(this.provinceIndex) : null;
            City city = this.cities != null && this.cityIndex != -1 ? (City)this.cities.get(this.cityIndex) : null;
            County county = null;//this.counties != null && this.countyIndex != -1 ? (County)this.counties.get(this.countyIndex) : null;
            Street street = null;//this.streets != null && this.streetIndex != -1 ? (Street)this.streets.get(this.streetIndex) : null;
            this.listener.onAddressSelected(province, city, county, street);
        }

    }

    @SuppressLint("WrongConstant")
    private void updateProgressVisibility() {
        ListAdapter adapter = this.listView.getAdapter();
        int itemCount = adapter.getCount();
        //this.progressBar.setVisibility(itemCount > 0 ? 8 : 0);
    }

    @SuppressLint("WrongConstant")
    private void retrieveProvinces() {
        //this.progressBar.setVisibility(0);
        this.addressProvider.provideProvinces(new AddressProvider.AddressReceiver<Province>() {
            public void send(List<Province> data) {
                DiquSelect.this.handler.sendMessage(Message.obtain(DiquSelect.this.handler, 0, data));
            }
        });
    }

    @SuppressLint("WrongConstant")
    private void retrieveCitiesWith(int provinceId) {
        //this.progressBar.setVisibility(0);
        this.addressProvider.provideCitiesWith(provinceId, new AddressProvider.AddressReceiver<City>() {
            public void send(List<City> data) {
                DiquSelect.this.handler.sendMessage(Message.obtain(DiquSelect.this.handler, 1, data));
            }
        });
    }

    @SuppressLint("WrongConstant")
    private void retrieveCountiesWith(int cityId) {
        //this.progressBar.setVisibility(0);
        this.addressProvider.provideCountiesWith(cityId, new AddressProvider.AddressReceiver<County>() {
            public void send(List<County> data) {
                //DiquSelect.this.handler.sendMessage(Message.obtain(DiquSelect.this.handler, 2, data));
            }
        });
    }

    @SuppressLint("WrongConstant")
    private void retrieveStreetsWith(int countyId) {
        this.progressBar.setVisibility(0);
        this.addressProvider.provideStreetsWith(countyId, new AddressProvider.AddressReceiver<Street>() {
            public void send(List<Street> data) {
                //DiquSelect.this.handler.sendMessage(Message.obtain(DiquSelect.this.handler, 3, data));
            }
        });
    }

    public OnAddressSelectedListener getOnAddressSelectedListener() {
        return this.listener;
    }

    public void setOnAddressSelectedListener(OnAddressSelectedListener listener) {
        this.listener = listener;
    }

    public void setAddressProvider(AddressProvider addressProvider) {
        this.addressProvider = addressProvider;
        if (addressProvider == null) {
            this.addressProvider = DEFAULT_ADDRESS_PROVIDER;
        }

    }





    class CityAdapter extends BaseAdapter {
        CityAdapter() {
        }

        public int getCount() {
            return DiquSelect.this.cities == null ? 0 : DiquSelect.this.cities.size();
        }

        public City getItem(int position) {
            return (City)DiquSelect.this.cities.get(position);
        }

        public long getItemId(int position) {
            return (long)this.getItem(position).id;
        }

        @SuppressLint("WrongConstant")
        public View getView(int position, View convertView, ViewGroup parent) {
            DiquSelect.CityAdapter.Holder holder;
            if (convertView == null) {
                convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_area, parent, false);
                holder = new DiquSelect.CityAdapter.Holder();
                holder.textView = (TextView)convertView.findViewById(R.id.textView);
                holder.imageViewCheckMark = (ImageView)convertView.findViewById(R.id.imageViewCheckMark);
                convertView.setTag(holder);
            } else {
                holder = (DiquSelect.CityAdapter.Holder)convertView.getTag();
            }

            City item = this.getItem(position);
            holder.textView.setText(item.name);
            boolean checked = DiquSelect.this.cityIndex != -1 && ((City)DiquSelect.this.cities.get(DiquSelect.this.cityIndex)).id == item.id;
            holder.textView.setEnabled(!checked);
            holder.imageViewCheckMark.setVisibility(checked ? 0 : 8);
            return convertView;
        }

        class Holder {
            TextView textView;
            ImageView imageViewCheckMark;

            Holder() {
            }
        }
    }

    class ProvinceAdapter extends BaseAdapter {
        ProvinceAdapter() {
        }

        public int getCount() {
            return DiquSelect.this.provinces == null ? 0 : DiquSelect.this.provinces.size();
        }

        public Province getItem(int position) {
            return (Province)DiquSelect.this.provinces.get(position);
        }

        public long getItemId(int position) {
            return (long)this.getItem(position).id;
        }

        @SuppressLint("WrongConstant")
        public View getView(int position, View convertView, ViewGroup parent) {
            DiquSelect.ProvinceAdapter.Holder holder;
            if (convertView == null) {
                convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_area, parent, false);
                holder = new DiquSelect.ProvinceAdapter.Holder();
                holder.textView = (TextView)convertView.findViewById(R.id.textView);
                holder.imageViewCheckMark = (ImageView)convertView.findViewById(R.id.imageViewCheckMark);
                convertView.setTag(holder);
            } else {
                holder = (DiquSelect.ProvinceAdapter.Holder)convertView.getTag();
            }

            Province item = this.getItem(position);
            holder.textView.setText(item.name);
            boolean checked = DiquSelect.this.provinceIndex != -1 && ((Province)DiquSelect.this.provinces.get(DiquSelect.this.provinceIndex)).id == item.id;
            holder.textView.setEnabled(!checked);
            holder.imageViewCheckMark.setVisibility(checked ? 0 : 8);
            return convertView;
        }

        class Holder {
            TextView textView;
            ImageView imageViewCheckMark;

            Holder() {
            }
        }
    }





    class OnCityTabClickListener implements View.OnClickListener {
        OnCityTabClickListener() {
        }

        public void onClick(View v) {
            DiquSelect.this.tabIndex = 1;
            DiquSelect.this.listView.setAdapter(DiquSelect.this.cityAdapter);
            if (DiquSelect.this.cityIndex != -1) {
                DiquSelect.this.listView.setSelection(DiquSelect.this.cityIndex);
            }

            DiquSelect.this.updateTabsVisibility();
            DiquSelect.this.updateIndicator();
        }
    }

    class OnProvinceTabClickListener implements View.OnClickListener {
        OnProvinceTabClickListener() {
        }

        public void onClick(View v) {
            DiquSelect.this.tabIndex = 0;
            DiquSelect.this.listView.setAdapter(DiquSelect.this.provinceAdapter);
            if (DiquSelect.this.provinceIndex != -1) {
                DiquSelect.this.listView.setSelection(DiquSelect.this.provinceIndex);
            }

            DiquSelect.this.updateTabsVisibility();
            DiquSelect.this.updateIndicator();
        }
    }
}
